<template>
    <div>
        <a-button @click="startRecording" type="primary" :loading="loading">开始录音</a-button>
        <a-button @click="stopRecording">停止录音</a-button>
        <p>{{ transcript }}</p>
        <a-upload
            v-model:file-list="fileList"
            name="file"
            action="http://10.20.0.246:8083"
            :headers="headers"
            @change="handleFileChange"
            accept="wav"
            :before-upload="handleFileUpload"
        >
            <a-button>
                <upload-outlined></upload-outlined>
                Click to Upload
            </a-button>
        </a-upload>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { post } from '@/utils/http/Axios'

const transcript = ref('')
const loading = ref(false)
const audioChunks = []

let mediaRecorder

async function startRecording() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
        mediaRecorder = new MediaRecorder(stream)

        mediaRecorder.ondataavailable = event => {
            if (event.data.size > 0) {
                audioChunks.push(event.data)
            }
        }

        mediaRecorder.onstop = () => {
            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' })
            const audioDuration = audioChunks.length / mediaRecorder.stream.getTracks()[0].getSettings().sampleRate || 0

            console.log('音频长度（秒）：', audioDuration)
            downloadAudio(audioBlob)
            convertSpeechToText(audioBlob)
        }

        mediaRecorder.start()
        console.log('开始录制音频...')
    } catch (error) {
        console.error('获取音频权限失败:', error)
    }
}

function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop()
        console.log('停止录制音频...')
    }
}

function downloadAudio(audioBlob) {
    const downloadLink = document.createElement('a')
    downloadLink.href = URL.createObjectURL(audioBlob)
    downloadLink.download = 'recorded_audio.wav'
    document.body.appendChild(downloadLink)
    downloadLink.click()
    URL.revokeObjectURL(downloadLink.href)
}

async function convertSpeechToText(audioBlob) {
    try {
        loading.value = true
        const response = await post('/getWord', audioBlob)
        transcript.value = response.data
        loading.value = false
    } catch (error) {
        console.error('语音识别失败:', error)
        loading.value = false
    }
}

// 处理文件上传
function handleFileChange(file) {
    console.log('文件选择:', file)
}

// 处理上传前的操作
function handleFileUpload(file) {
    const formData = new FormData()
    formData.append('file', file)
    // 添加更多上传前的逻辑
    return formData
}
</script>
